package com.sskj.lib.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.hardware.fingerprint.FingerprintManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bulong.rudeness.RudenessScreenHelper;
import com.bumptech.glide.load.data.FileDescriptorLocalUriFetcher;
import com.jakewharton.rxbinding2.widget.RxAdapterView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okserver.OkDownload;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.ImgUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.R;
import com.sskj.lib.adapter.ArrowAdapter;
import com.sskj.lib.http.JsonCallBack;
import com.sskj.lib.widget.RxNoLifeFingerPrinter;
import com.yalantis.ucrop.util.FileUtils;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import io.reactivex.observers.DisposableObserver;
import zwh.com.lib.FPerException;
import zwh.com.lib.IdentificationInfo;
import zwh.com.lib.RxFingerPrinter;

import static zwh.com.lib.CodeException.FINGERPRINTERS_FAILED_ERROR;
import static zwh.com.lib.CodeException.FINGERPRINTERS_RECOGNIZE_FAILED;
import static zwh.com.lib.CodeException.HARDWARE_MISSIING_ERROR;
import static zwh.com.lib.CodeException.KEYGUARDSECURE_MISSIING_ERROR;
import static zwh.com.lib.CodeException.NO_FINGERPRINTERS_ENROOLED_ERROR;
import static zwh.com.lib.CodeException.PERMISSION_DENIED_ERROE;

public class TipUtil {
    public static MaterialDialog getTip(Context context, String content, OnTipSure onTipSure) {
        return getTip(context, content, context.getString(R.string.lib_sure), onTipSure);
    }

    public static MaterialDialog getTip(Context context, String content, boolean isCancel, OnTipSure onTipSure) {
        return new MaterialDialog.Builder(context)
                .title(App.INSTANCE.getString(R.string.lib_tip))
                .content(content)
                .cancelable(false)
                .autoDismiss(false)
                .positiveText(App.INSTANCE.getString(R.string.lib_sure))
//                .negativeText("")
                .onAny((dialog, which) -> {
                    if (which == DialogAction.POSITIVE) {
                        dialog.dismiss();
                        onTipSure.onSure();
                    } else if (which == DialogAction.NEGATIVE) {
                        dialog.dismiss();
                    }
                }).build();
    }

    public static MaterialDialog getTip(Context context, String content, String sureMsg, OnTipSure onTipSure) {
        return new MaterialDialog.Builder(context)
                .title(R.string.lib_tip)
                .content(content)
                .positiveText(sureMsg)
                .negativeText(R.string.lib_cancel)
                .onAny((dialog, which) -> {
                    if (which == DialogAction.POSITIVE) {
                        dialog.dismiss();
                        onTipSure.onSure();
                    } else if (which == DialogAction.NEGATIVE) {
                        dialog.dismiss();
                    }
                }).build();
    }

    public static MaterialDialog getTip(Context context, String content, String sureMsg, OnTipSure2 onTipSure) {
        return new MaterialDialog.Builder(context)
                .title(R.string.lib_tip)
                .content(content)
                .positiveText(sureMsg)
                .negativeText(R.string.lib_cancel)
                .onAny((dialog, which) -> {
                    if (which == DialogAction.POSITIVE) {
                        dialog.dismiss();
                        onTipSure.onSure();
                    } else if (which == DialogAction.NEGATIVE) {
                        dialog.dismiss();
                        onTipSure.onCancel();
                    }
                }).build();
    }

    public static MaterialDialog getTip(Context context, String title, String content, String sureMsg, OnTipSure onTipSure) {
        return new MaterialDialog.Builder(context)
                .title(title)
                .content(content)
                .positiveText(sureMsg)
                .negativeText(R.string.lib_cancel)
                .onAny((dialog, which) -> {
                    if (which == DialogAction.POSITIVE) {
                        dialog.dismiss();
                        onTipSure.onSure();
                    } else if (which == DialogAction.NEGATIVE) {
                        dialog.dismiss();
                    }
                }).build();
    }

    public static void showGonggao(Context context, String content) {
        MaterialDialog dialog = new MaterialDialog.Builder(context)
                .customView(R.layout.lib_dialog_gonggao, false)
                .autoDismiss(false)
                .cancelable(false)
                .show();
        View customeView = dialog.getCustomView();

        ((TextView) customeView.findViewById(R.id.tvContent)).setText(content);
        ClickUtil.click(customeView.findViewById(R.id.btSure), () -> {
            dialog.dismiss();
        });
    }

    public static MaterialDialog getExitTip(Activity activity, String content, OnTipSure onTipSure) {
        MaterialDialog dialog = new MaterialDialog.Builder(activity)
                .customView(R.layout.lib_dialog_exit, false)
                .autoDismiss(true)
                .cancelable(true)
                .show();
        View customView = dialog.getCustomView();
        TextView tvContent = customView.findViewById(R.id.tvContent);
        tvContent.setText(content);
        ClickUtil.click(dialog.getCustomView().findViewById(R.id.tvSure), () -> {
            onTipSure.onSure();
        });
        ClickUtil.click(dialog.getCustomView().findViewById(R.id.tvCancel), () -> {
            dialog.dismiss();
        });
        return dialog;
    }

    public static MaterialDialog getSureTip(Activity activity, String title, String content, OnTipSure onTipSure) {
        MaterialDialog dialog = new MaterialDialog.Builder(activity)
                .customView(R.layout.lib_dialog_sure, false)
                .autoDismiss(true)
                .cancelable(true)
                .show();
        View customView = dialog.getCustomView();
        TextView tvContent = customView.findViewById(R.id.tvContent);
        TextView tvTitle = customView.findViewById(R.id.tvTitle);
        tvContent.setText(content);
        tvTitle.setText(title);
        ClickUtil.click(dialog.getCustomView().findViewById(R.id.btSure), () -> {
            onTipSure.onSure();
        });
        return dialog;
    }

    public static MaterialDialog getSureTip(Activity activity, String content, OnTipSure onTipSure) {
        return getSureTip(activity, App.INSTANCE.getString(R.string.lib_tip), content, onTipSure);
    }

    public static MaterialDialog getSureCancelTip(Activity activity, String content, OnTipSure onTipSure) {
        MaterialDialog dialog = new MaterialDialog.Builder(activity)
                .customView(R.layout.lib_dialog_sure_cancel, false)
                .autoDismiss(true)
                .cancelable(true)
                .show();
        View customView = dialog.getCustomView();
        TextView tvContent = customView.findViewById(R.id.tvContent);
        tvContent.setText(content);
        ClickUtil.click(dialog.getCustomView().findViewById(R.id.btSure), () -> {
            onTipSure.onSure();
        });
        ClickUtil.click(dialog.getCustomView().findViewById(R.id.btCancel), () -> {
            dialog.dismiss();
        });
        return dialog;
    }

    public static AlertDialog reserveSuccess(Activity activity, String content) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.libDialogBackgroundNull);
        View dialogView = LayoutInflater.from(activity).inflate(R.layout.lib_dialog_success_reserve, null, false);
        builder.setView(dialogView);
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        TextView tvContent = dialogView.findViewById(R.id.tv_dragon);
        tvContent.setText(content);
        ClickUtil.click(dialogView.findViewById(R.id.tv_close), () -> {
            dialog.dismiss();
        });
        dialog.show();
        return dialog;
    }


    public static AlertDialog reserveTip(Activity activity, String dragonType, String dragonDay, String money, OnTipSure onTipSure) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.libDialogBackgroundNull);
        View dialogView = LayoutInflater.from(activity).inflate(R.layout.lib_dialog_tip_reserve, null, false);
        builder.setView(dialogView);
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        TextView tv_dragon = dialogView.findViewById(R.id.tv_dragon);
        TextView tv_days_heyue = dialogView.findViewById(R.id.tv_days_heyue);
        TextView tv_acounts_shuijing = dialogView.findViewById(R.id.tv_acounts_shuijing);
        tv_dragon.setText(activity.getString(R.string.benciyuyue, dragonType));
        tv_days_heyue.setText(activity.getString(R.string.jitianheyue, dragonDay));
        tv_acounts_shuijing.setText(activity.getString(R.string.zhifushuijing, money));
        ClickUtil.click(dialogView.findViewById(R.id.btn_confirm), () -> {
            onTipSure.onSure();
            dialog.dismiss();
        });
        ClickUtil.click(dialogView.findViewById(R.id.tv_close), () -> {
            dialog.dismiss();
        });
        dialog.show();
        return dialog;
    }


    public static AlertDialog turntableTip(Activity activity, String amount, String name, OnTipSure onTipSure) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.libDialogBackgroundNull);
        View dialogView = LayoutInflater.from(activity).inflate(R.layout.lib_dialog_tip_turntable, null, false);
        builder.setView(dialogView);
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        TextView title = dialogView.findViewById(R.id.tv0);
        title.setText(activity.getString(R.string.gongxihuode, amount, name));
        ClickUtil.click(dialogView.findViewById(R.id.btn_confirm), () -> {
            onTipSure.onSure();
            dialog.dismiss();
        });
        ClickUtil.click(dialogView.findViewById(R.id.tv_close), () -> {
            dialog.dismiss();
        });
        dialog.show();
        return dialog;
    }

    public static AlertDialog buyTip(Activity activity, String dragonType, String dragonDay, String money, String shuijing) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.libDialogBackgroundNull);
        View dialogView = LayoutInflater.from(activity).inflate(R.layout.lib_dialog_tip_buy, null, false);
        builder.setView(dialogView);
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        TextView tv_dragon = dialogView.findViewById(R.id.tv_dragon);
        TextView tv_days_heyue = dialogView.findViewById(R.id.tv_days_heyue);
        TextView tv_acounts_shuijing = dialogView.findViewById(R.id.tv_acounts_shuijing);
        tv_dragon.setText(activity.getString(R.string.gongxiqianggou, dragonType));
        tv_days_heyue.setText(activity.getString(R.string.jitianheyue, dragonDay));
        tv_acounts_shuijing.setText(activity.getString(R.string.qianggoumoney, money, shuijing));
        ClickUtil.click(dialogView.findViewById(R.id.btn_confirm), () -> {
            dialog.dismiss();
        });
        ClickUtil.click(dialogView.findViewById(R.id.tv_close), () -> {
            dialog.dismiss();
        });
        dialog.show();
        return dialog;
    }


    public static AlertDialog orderAppeal(Activity activity, List<String> payTypes, OnTipEdit onTipSure) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.libDialogBackgroundNull);
        View dialogView = LayoutInflater.from(activity).inflate(R.layout.lib_dialog_order_appeal, null, false);
        builder.setView(dialogView);
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
//        Spinner spinner = dialogView.findViewById(R.id.spinner);
//        ArrowAdapter spinnerTypeAdapter = new ArrowAdapter(activity,
//                R.layout.lib_spinner_type, payTypes);
//        spinnerTypeAdapter.setDropDownViewResource(R.layout.lib_spinner_type_drop);
//        spinner.setAdapter(spinnerTypeAdapter);
//        spinner.setSelection(0);
//        spinner.setDropDownVerticalOffset(10);
        EditText et_liuyan = dialogView.findViewById(R.id.et_liuyan);
//        RxAdapterView.itemSelections(spinner)
//                .subscribe(pos -> {
//
//                });
        ClickUtil.click(dialogView.findViewById(R.id.tv_close), () -> {
            dialog.dismiss();
        });
        ClickUtil.click(dialogView.findViewById(R.id.btn_submit), () -> {
            if (TextUtils.isEmpty(et_liuyan.getText().toString())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.libShensuyuanyin));
                return;
            }
            onTipSure.onSure(et_liuyan.getText().toString());
            dialog.dismiss();
        });
        dialog.show();
        return dialog;
    }


    public static void qrcode(Activity activity, String imgUrl) {
        MaterialDialog dialog = new MaterialDialog.Builder(activity)
                .customView(R.layout.lib_qrcode, false)
                .autoDismiss(true)
                .cancelable(true)
                .show();
        View contentView = dialog.getCustomView();
        ImageView iv_qrcode = contentView.findViewById(R.id.iv_qrcode);
        TextView tv_save = contentView.findViewById(R.id.tv_save);
        ImageUtil.setImage(imgUrl, iv_qrcode);
        ClickUtil.click(300, tv_save, () -> {
            OkGo.<File>get(imgUrl).execute(new FileCallback() {
                @Override
                public void onSuccess(Response<File> response) {
                    ToastUtil.showShort("保存成功");
                    //保存图片后发送广播通知更新数据库
                    Uri uri = Uri.fromFile(response.body());
                    activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                    dialog.dismiss();
                }
            });
        });

    }


    @SuppressLint("NewApi")
    @TargetApi(23)
    private static boolean confirmFinger(Context context) {
        FingerprintManager manager = context.getSystemService(FingerprintManager.class);

        boolean isDeviceSupport = true;

        //android studio 上，没有这个会报错
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT)
                != PackageManager.PERMISSION_GRANTED) {
            isDeviceSupport = false;
        }
        //判断硬件是否支持指纹识别
        if (!manager.isHardwareDetected()) {
            isDeviceSupport = false;
        }
        //判断 是否开启锁屏密码

//        if (mKeyManager.isKeyguardSecure()) {
//            publishSubject.onNext(new IdentificationInfo(KEYGUARDSECURE_MISSIING_ERROR));
//            isDeviceSupport = false;
//        }
        //判断是否有指纹录入
        if (!manager.hasEnrolledFingerprints()) {
            isDeviceSupport = false;
        }

        return isDeviceSupport;
    }

    public static void getFingerTip(Activity activity, OnTipSure onTipSure) {
        if (!confirmFinger(activity)) {
            ToastUtil.showShort("请前往设置开启指纹解锁");
            return;
        }


        RxNoLifeFingerPrinter rxFingerPrinter = new RxNoLifeFingerPrinter(activity);
        MaterialDialog dialog = new MaterialDialog.Builder(activity)
                .customView(R.layout.lib_dialog_finger_check, false)
                .autoDismiss(false)
                .cancelable(false)
                .show();


        DisposableObserver<IdentificationInfo> observer =
                new DisposableObserver<IdentificationInfo>() {
                    @Override
                    protected void onStart() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        System.out.println(e.toString());

                    }

                    @Override
                    public void onComplete() {
                        System.out.println("complete");
                    }

                    @Override
                    public void onNext(IdentificationInfo info) {
                        if (info.isSuccessful()) {//识别成功
                            if (onTipSure != null) {
                                dialog.dismiss();
                                onTipSure.onSure();
                            }
//                            Toast.makeText(FingerActivity.this, "指纹识别成功", Toast.LENGTH_SHORT).show();
                        } else {//识别失败 获取错误信息
                            FPerException exception = info.getException();
                            if (exception != null && exception.getCode() != KEYGUARDSECURE_MISSIING_ERROR) {
                                Toast.makeText(activity, exception.getDisplayMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                };
        rxFingerPrinter.begin().subscribe(observer);//RxfingerPrinter会自动在onPause()时暂停指纹监听，onResume()时恢复指纹监听)


        ClickUtil.click(dialog.getCustomView().findViewById(R.id.tvCancel), () -> {
            dialog.dismiss();
        });

    }


    public interface OnTipEdit {
        void onSure(String string);

    }

    public interface OnTipSure {
        void onSure();

    }

    public interface OnTipSure2 {
        void onSure();

        void onCancel();
    }
}
